<?php

namespace App\Service\Message\v1_1_2;

use App\Constants\ErrorCode;
use App\Constants\InviteVideoCode;
use App\Helpers\ConfigUtil;
use App\Model\CallBase;
use App\Model\User;
use App\Model\UserCoin;
use App\Model\UserProfile;
use App\Model\VideoCall;
use App\Model\VideoCallAuditConfig;
use App\Model\VoiceCall;
use App\Service\CallBaseService;
use App\Service\ServiceTrait\GetUserInfoTrait;

class QuickCallService extends CallBaseService
{
    use GetUserInfoTrait;
    protected function RoVerifyList()
    {
        return [
            'call_type' => 'required|string'
        ];
    }
    public function handle()
    {
        $userId = $this->getUserId();
        $callType = $this->request->input('call_type', 1);
        $hostId = $this->request->input('user_id');

        if (VoiceCall::checkUserChatting($userId) || VideoCall::checkUserChatting($userId)) {
            return $this->setError(ErrorCode::HOST_BUSY, '当前正在通话，不能使用该功能～');
        }

        if (VoiceCall::checkUserChatting($hostId) || VideoCall::checkUserChatting($hostId)) {
            return $this->setError(ErrorCode::HOST_BUSY, '对方当前正在通话，不能使用该功能～');
        }
        $callCls = $callType == VoiceCall::CALL_TYPE ? VoiceCall::class : VideoCall::class;

        $callFrom = CallBase::FROM_QUICK_MESSAGE;
        $callMark = 1;
        if ($callType == VideoCall::CALL_TYPE && VideoCall::getInviteVideoTotal($userId) < InviteVideoCode::TOTAL_MAX_ANSWER_NUM) {
            $callFrom = VideoCall::FROM_INVITE_CALL;
            $callMark =3;
//            list($userId,$hostId) = array($hostId,$userId);
//                $freeCall = 1;
        }

        $hostProfile = $this->getUserInfo($hostId);
        $coinSetting = $callType == VoiceCall::CALL_TYPE ? $hostProfile->coin_setting : $hostProfile->video_coin_setting;

        if ($callFrom != VideoCall::FROM_INVITE_CALL)
        {
            $userCoin = UserCoin::getUserInfo($userId);

            if (!$userCoin || !$userCoin['total_coin'] || $userCoin['total_coin'] < $coinSetting) {
                return $this->setError(ErrorCode::COIN_NOT_ENOUGH, '你的余额不足，请充值后再试~');
            }
        }

        if ($callFrom == VideoCall::FROM_INVITE_CALL)
        {
            list($userId,$hostId) = array($hostId,$userId);
        }
        $ret = $callCls::addRecord($userId, $hostId, $callFrom, $coinSetting,$callMark);
        if ($callFrom == VideoCall::FROM_INVITE_CALL)
        {
            list($userId,$hostId) = array($hostId,$userId);
        }
        //呼叫回调
        $this->callHook($hostId, $userId);
        log_info(__CLASS__ . "=={$callCls}=={$userId}==HostId:{$hostId}");
        // 鉴黄配置
        $config = (new VideoCallAuditConfig())->getConfig($userId);

        return [
            'coin_setting' => $coinSetting,
            'user_info' => UserProfile::buildHostItem(UserProfile::getProfile($hostId)),
            'support_face' => User::checkFaceSupport($hostId),
            'jHConfig' => $config,
        ];
    }
}